/**
 * Used to take Documents in and out of the database.
 * 
 * @author Chris Baillie.
 */

package application;

import java.io.*;

import javax.swing.text.Document;
import javax.swing.text.rtf.*;
import java.util.ArrayList;

public class DocumentManager {

	//Instance Variables
	database.DatabaseWrapper db = new database.DatabaseWrapper();	//Link to the database
	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));	//User input
	
	//Constructor
	public DocumentManager()
	{
		/* Nothing to do! */
	}

	/**
	 * Prompts the user for the location of documents
	 * and proceeds to read them in.
	 */
	public void getDocuments()
	{
		//Get details about document
		String filename = getInfo("Please enter the filename of the file(Relative to 'Docs'): ");
		String subject = getInfo("What is the subject of the document: ");
		String author = getInfo("Who is the author of the document: ");
		String response = getInfo("'" + subject + "' by '" + author + "'(" + filename + "'). Is this correct?(y/n): ");

		if(response.equalsIgnoreCase("y") || (response.indexOf("y") != -1)){
		
			if(filename.indexOf(".txt") != -1)
				getTxtFileContents(author,subject,filename);
			else if(filename.indexOf(".rtf") != 1)
				getRtfFileContents(author,subject,filename);
			else
				System.out.println("Sorry, but we don't know how to handle files of that type.");
			
		}
	}
	
	/**
	 * Gets a list of the essay subjects stored
	 * in the database.
	 */
	public ArrayList<String> getSubjects()
	{
		ArrayList<String> subjects = new ArrayList<String>();
		subjects = db.getSubjects();
		if(subjects.size() == 0)
			System.out.println("There are no subjects stored.");
		else {
			//Display list of subjects
			for(int i=0;i<subjects.size();i++)
				System.out.print((String)subjects.get(i) + "    ");
		}
		return subjects;
	}
	
	public ArrayList<String> getEssay(ArrayList<String> subjects)
	{
		ArrayList<String> authors = new ArrayList<String>();
		ArrayList<String> details = new ArrayList<String>();
		//Find out which subject the user wants
		String response = getInfo("\nWhich subject would you like to display: "),subject = "";
		subject = response;
		int count = 0;
		if(response != ""){
			//Check the subject is valid
			for(int i=0;i<subjects.size();i++){
				count++;
				if(response.equals((String)subjects.get(i))){
					//Subject is valid... get the essays
					authors = db.getEssay(response);
					if(authors.size() != 0){
						//Display the subjects and authors
						for(int j=0;j<authors.size();j++)
							System.out.println(j + ". " + response + " by " + (String)authors.get(j) + ".");
					} else
						System.out.println("There were no essays matching that subject.");
				}
			}
			//Let's get the essay proper
			response = getInfo("Enter the number of the essay that you want to display: ");
			int numRes = Integer.parseInt(response);
			if((numRes >= 0) && (numRes <= count)){
				details = db.getWholeEssay(subject,(String)authors.get(numRes));
			}
		}
		return details;
	}
	
	/**
	 * Handles .txt files coming into the system.
	 */
	public void getTxtFileContents(String author, String subject, String filename)
	{
		BufferedReader br = null;
		String temp = "", contents = "";
		Essay doc = new Essay(subject, author);
		try {
			br = new BufferedReader(new FileReader(filename));
		} catch (Exception e) {
			
			//We couldn't find the file... uh oh!
			
			System.err.println("File not found: \"" + filename + "\".");
			e.printStackTrace();
		}
		try{
			temp = br.readLine();
		} catch (Exception e){
			
			//No data came in.
			
			System.err.println("IO Exception.");
			e.printStackTrace();
		}
		while(temp != null){
			if(!temp.equals(""))
				contents += temp;
			try {
				temp = br.readLine();
			} catch (Exception e) {
				
				//No data came in.
				
				System.err.println("IO Exception.");
				e.printStackTrace();
			}
		}
		
		//Setup up the documents and INSERT
		doc.setContents(contents.trim().substring(3));
		db.addEssay(subject,author);
		db.addParagraphs(doc.getParagraphs());		
	}
	
	/**
	 * Handles .rtf files coming into the system.
	 */
	public void getRtfFileContents(String author, String subject, String filename)
	{
		FileInputStream file = null;
		String contents = "";
		Essay essay = new Essay(subject,author);
		try {
			file = new FileInputStream(filename);
		} catch (Exception e) {
			
				//FileNotFound
				System.out.println("File Not Found Exception");
				e.printStackTrace();
		}
		RTFEditorKit rtf = new RTFEditorKit();
		Document doc = (Document)rtf.createDefaultDocument();
		try {
			rtf.read(file, doc, 0);
			contents = doc.getText(0, doc.getLength());
		} catch (Exception e){
			
				//Nothing came in
				System.err.println("IO Exception");
				e.printStackTrace();
		}
		
		//System.out.println(contents);
		//Setup up the documents and INSERT
		essay.setContents(contents.trim().substring(3));
		db.addEssay(subject,author);
		db.addParagraphs(essay.getParagraphs());
	}
	
	public String getInfo(String question)
	{
		System.out.print(question);
		String response = "";
		try {
			response = in.readLine();
		} catch (Exception e){
			System.out.println("BufferedReader Exception");
			e.printStackTrace();
		}
		return response;
	}
	
	/**
	 * Destructor to close the database connection when we're done
	 */
	public void finalize()
	{
		db.finalize();
	}
}
